<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      #content {
        width: 200px;
        height: 200px;
        line-height: 200px;
        background-color: #ccc;
        margin: 0 auto;
        font-size: 60px;
        text-align: center;
        color: #000;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <div id="content"></div>
    <button>防抖</button>
    <button>截流</button>
    <!-- 实际应用 -->
    <input type="text">
    <script>
      let oButton1 = document.getElementsByTagName('button')[0];
      let oButton2 = document.getElementsByTagName('button')[1];
      let fn = () => {
        console.log('我点击了');
      }
      let deBounce = (fn, delay) => {
        let timer = null;
        return function (...agrs) {
          if (timer) {
            clearTimeout(timer);
          }
          timer = setTimeout(() => {
            fn(...agrs);
          }, delay);
        }
      }
      // 节流,当持续触发事件时,保证一定时间段内只调用一次事件处理函数
      let throttle = (fn, delay) => {
        let flag = true;
        return function (...args) {
            if (!flag) return;
            flag = false;
            setTimeout(() => {
                fn(...args);
                flag = true;
            }, delay)
        }
      }
      oButton1.onclick = deBounce(fn, 500);
      oButton2.onclick = throttle(fn, 500);
      // 没有做防抖之前
      let num = 1;
      let oDiv = document.getElementById('content');
      let changeNum = () => {
        oDiv.innerHTML = num ++;
      };
      // 绑定没有做防抖之前
      // oDiv.onmousemove = changeNum;
      // 添加防抖
      let deBouce = (fn, delay) => {
        let timer = null;
        return () => {
          if (timer) {
            clearTimeout(timer);
          }
          timer = setTimeout(() => {
            fn();
          }, delay);
        }
      }
      oDiv.onmousemove = deBouce(changeNum, 500);
      let oInput = document.getElementsByTagName('input')[0];
      let ajax = (content) => {
        let message = content;
        console.log('--------', content);
        let json = { message };
        console.log(JSON.stringify(json));
      }
      let doAjax = deBouce(ajax, 2000);
      // 不使用防抖
      // oInput.addEventListener('keyup', (e) => {
      //   console.log('---addEventListener--', e.target.value);
      // })
      // 使用防抖
      oInput.addEventListener('keyup', (e) => {
        doAjax(e.target.value);
        // console.log('---addEventListener--', e.target.value);
      })
    </script>
  </body>
</html>